package com.seata.demo.cloud.controller;

import com.seata.demo.cloud.dao.AccountDao;
import com.seata.demo.cloud.dto.AccountDTO;
import com.seata.demo.cloud.service.AccountTccAction;
import io.seata.core.context.RootContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/account")
public class AccountController {
    Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    AccountDao accountDao;
    @Autowired
    AccountTccAction accountTccAction;

    @PostMapping("/reduceBalance")
    @Transactional(rollbackFor = Throwable.class)
    public boolean reduceBalance (@RequestBody AccountDTO accountDTO) throws Exception{
        logger.info("[reduceBalance xid={},{}]", RootContext.getXID(),accountDTO);
        long userId = accountDTO.getUserId();
        int amount = accountDTO.getAmount();
        Integer balance = accountDao.getBalance(userId);
        if(balance!=null || balance <amount){
            throw new RuntimeException("余额不足");
        }
        int updateCount = accountDao.reduceBalance(userId,amount);
        logger.info("更新成功");
        return true;
    }

    @PostMapping("/reduceBalanceTCC")
    @Transactional(rollbackFor = Throwable.class)
    public boolean reduceBalanceTCC (@RequestBody AccountDTO accountDTO) throws Exception{
        logger.info("[reduceBalanceTCC xid={},{}]", RootContext.getXID(),accountDTO);
        accountTccAction.reduceBalance(accountDTO);
        return true;
    }

    @GetMapping("/getBalance")
    public Integer getBalance(@RequestParam("userId")  Long userId){
        Integer bl = accountDao.getBalance(userId);
        logger.info("[getBalance]查询余额完成,{}",bl);
        return bl;
    }
}
